package view;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.net.URL;

import javax.swing.ImageIcon;
import javax.swing.JPanel;

/**
 * A basic panel which just holds an image.
 * 
 * @author Bill
 *
 */
public class ImagePanel extends JPanel{

	private static final long serialVersionUID = 1L;
	private ImageIcon image;
	private int numLayers = 0;
	private int rotation = 0;
	
	public ImagePanel(String fileName){
		super();
		URL url = this.getClass().getResource("/graphics/"+fileName);
		image = new ImageIcon(url);
		this.setOpaque(false);
		setPreferredSize(new Dimension(image.getIconWidth(),image.getIconHeight()));
		setSize(new Dimension(image.getIconWidth(),image.getIconHeight()));
	}
	
	public ImagePanel(String fileName, int width, int height){
		this(fileName);
		this.setPreferredSize(new Dimension(width,height));
		this.setSize(width,height);
	}
	
	public ImagePanel(ImageIcon im){
		super();
		this.image = im;
		this.setOpaque(false);
		setPreferredSize(new Dimension(image.getIconWidth(),image.getIconHeight()));
		setSize(new Dimension(image.getIconWidth(),image.getIconHeight()));
	}
	
	@Override
	public void paintComponent(Graphics g){
		super.paintComponent(g);
		Graphics2D g2d = (Graphics2D)g;
		g2d.translate(this.getWidth()/2, this.getHeight()/2);
		g2d.rotate(this.rotation*Math.PI/180);
		g2d.translate(-image.getImage().getWidth(null)/2, -image.getImage().getHeight(null)/2);
		g2d.drawImage(image.getImage(), 0, 0, null);
	}
	
	/**
	 * Adds an image on top of the current image
	 * @param fileName
	 */
	public void addImageLayer(String fileName){
		ImagePanel newLayer = new ImagePanel(fileName);
		this.add(newLayer);
		this.numLayers++;
		this.repaint();
	}
	
	/**
	 * removes the top image on the stack of layers, if there is more than zero layers
	 */
	public void removeTopImageLayer(){
		if(numLayers != 0){
			ImagePanel topLayer = (ImagePanel)this.getComponent(--numLayers);
			this.remove(topLayer);
			this.repaint();
		}
	}
	
	/**
	 * Getters and Setters
	 */
	public int getRotation() {
		return rotation;
	}

	public void setRotation(int rotation) {
		this.rotation = rotation;
	}
	
	public ImageIcon getImage() {
		return image;
	}

	public void setImage(ImageIcon image) {
		this.image = image;
	}

}
